package com.bruce.spring.http.service;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serial;
import java.util.Enumeration;

/**
 * Created by bruce in 2025/6/18 21:42
 */
@Component
public class RequestLogFilter extends HttpFilter {
    private static final Logger log = LoggerFactory.getLogger(RequestLogFilter.class);

    @Serial
    private static final long serialVersionUID = -8372457981640874402L;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        // 打印请求基本信息
        // System.out.println("=== Request Info ===");
        // log.info("Method: {}, URL: {}", req.getMethod(), req.getRequestURL());
        // log.info("req.getQueryString(): {}", req.getQueryString());
        // log.info("req.getParameterMap(): {}", JsonUtil.toJson(req.getParameterMap()));
        //
        // // 打印请求头
        // System.out.println("--- Headers ---");
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        //     String headerName = headerNames.nextElement();
        //     log.info("request header: {}, value: {}", headerName, req.getHeader(headerName));
        // }
        String s = req.getRemoteAddr() + ":" + req.getRemotePort();
        // log.info("request remote: {}, path:{}", s, req.getRequestURI());

        super.doFilter(request, response, chain);

        // HttpServletResponse resp = (HttpServletResponse) response;
        // for (String headerName : resp.getHeaderNames()) {
        //     log.info("response header: {}, value: {}", headerName, resp.getHeader(headerName));
        // }
    }
}
